package cn.trip.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.trip.pojo.Trip_address;
import cn.trip.pojo.Trip_bill;
import cn.trip.pojo.Trip_brands;
import cn.trip.pojo.Trip_place;
import cn.trip.pojo.Trip_product;
import cn.trip.pojo.Trip_room;
import cn.trip.pojo.Trip_theme;
import cn.trip.pojo.Trip_tourist;
import cn.trip.pojo.Trip_user;
import cn.trip.service.index.IndexService;
import cn.trip.utils.Constants;
import cn.trip.utils.PageSupport;


@Controller
@RequestMapping(value="/index")
public class IndexController {
	
	private Logger logger = Logger.getLogger(IndexController.class);
	
	@Resource
	private IndexService indexService;
	
	@RequestMapping(value="/index.do")
	public String indexDo(Model model){
		List<Trip_brands> brands = null;
		List<Trip_product> hotelProducts = null;
		List<Trip_product> ticketProducts = null;
		List<Trip_theme> themes = null;
		//页面容量
		//当前页码
		Integer currentPageNo =1;
		try {
			brands = indexService.getAllList(currentPageNo, 8);
			hotelProducts = indexService.getAllListByPtype(2,null,null,0,currentPageNo, 8);
			ticketProducts = indexService.getAllListByPtype(1,null,null,0,currentPageNo, 8);
			themes = indexService.getThemes(0);
			System.out.println(themes.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("themes",themes);
		model.addAttribute("brands",brands);
		model.addAttribute("hotel",hotelProducts);
		model.addAttribute("ticket",ticketProducts);
		return "index/index";
	}
	
	@RequestMapping(value="/search")
	public String search(Model model,@RequestParam(value="p_type",required=false)Integer p_type,
						@RequestParam(value="pageIndex",required=false)String pageIndex,
						@RequestParam(value="area",required=false)String area,@RequestParam(value="desc",required=false)String desc,
						@RequestParam(value="title",required=false)String title,
						@RequestParam(value="p_Name",required=false)String p_Name,@RequestParam(value="th_id",required=false)String thid){
		logger.debug("p_type===================>"+p_type);
		logger.debug("area====================>"+area);
		logger.debug("desc======================>"+desc);
		logger.debug("title=====================>"+title);
		logger.debug("p_Name=====================>"+p_Name);
		logger.debug("th_id======================>"+thid);
		List<Trip_brands> brandsDesc = null;
		//页面容量
		int pageSize = Constants.pageSize;
		//当前页码
		Integer currentPageNo =1;
		int th_id = 0;
		if(thid != null){
			th_id = Integer.parseInt(thid);
		}
		if(pageIndex != null){
			try{
				currentPageNo = Integer.valueOf(pageIndex);
			}catch (NumberFormatException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		if(p_type == 4){
			List<Trip_brands> brands = null;
			//总数量（表）
			int totalCount = 0;
			try {
				totalCount = indexService.allCount();
			} catch (Exception e) {
				e.printStackTrace();
			}
			//总页数
			PageSupport pages = new PageSupport();
			pages.setCurrentPageNo(currentPageNo);
			pages.setPageSize(pageSize);
			pages.setTotalCount(totalCount);
			int totalPageCount = pages.getTotalPageCount();
			//控制首页和尾页
			if(currentPageNo < 1){
				currentPageNo = 1;
			}else if(currentPageNo > totalPageCount){
				currentPageNo = totalPageCount;
			}
			brands = indexService.getBrands(area, desc, title, currentPageNo, 16);
			brandsDesc = indexService.getBrandsDesc();
			int brandCount = indexService.allCount();
			model.addAttribute("pages",pages);
			model.addAttribute("brands",brands);
			model.addAttribute("brandsDesc",brandsDesc);
			model.addAttribute("brand",brandCount);
			model.addAttribute("p_type",p_type);
		}else if(p_type==1){
			List<Trip_product> products = null;
			List<Trip_place> places = null;
			List<Trip_theme> themes = null;
			Integer ticketcount = 0;
			//总数量（表）
			int totalCount = 0;
			try {
				totalCount = indexService.partCount(p_type);
			} catch (Exception e) {
				e.printStackTrace();
			}
			//总页数
			PageSupport pages = new PageSupport();
			pages.setCurrentPageNo(currentPageNo);
			pages.setPageSize(pageSize);
			pages.setTotalCount(totalCount);
			int totalPageCount = pages.getTotalPageCount();
			//控制首页和尾页
			if(currentPageNo < 1){
				currentPageNo = 1;
			}else if(currentPageNo > totalPageCount){
				currentPageNo = totalPageCount;
			}
			try {
				products = indexService.getAllListByPtype(p_type,area,p_Name,th_id,currentPageNo, 16);
				places = indexService.getPlaces();
				themes = indexService.getThemes(0);
				ticketcount = indexService.getPlaceCount(p_type,area,p_Name,th_id);
			} catch (Exception e) {
				e.printStackTrace();
			}
			model.addAttribute("themes",themes);
			model.addAttribute("products",products);
			model.addAttribute("places",places);
			model.addAttribute("ticketcount",ticketcount);
			return "index/searchTicket";
		}else if(p_type==2){
			List<Trip_product> products = null;
			Integer hotelcount = 0;
			//总数量（表）
			int totalCount = 0;
			try {
				totalCount = indexService.allCount();
			} catch (Exception e) {
				e.printStackTrace();
			}
			//总页数
			PageSupport pages = new PageSupport();
			pages.setCurrentPageNo(currentPageNo);
			pages.setPageSize(pageSize);
			pages.setTotalCount(totalCount);
			int totalPageCount = pages.getTotalPageCount();
			//控制首页和尾页
			if(currentPageNo < 1){
				currentPageNo = 1;
			}else if(currentPageNo > totalPageCount){
				currentPageNo = totalPageCount;
			}
			try {
				products = indexService.getAllListByPtype(p_type,area,p_Name,th_id,currentPageNo, 16);
				hotelcount = indexService.getPlaceCount(p_type,area,p_Name,th_id);
			} catch (Exception e) {
				e.printStackTrace();
			}
			model.addAttribute("products",products);
			model.addAttribute("hotelcount",hotelcount);
			return "index/searchHotel";
		}
		
		return "index/search";
	}
	
	
	@RequestMapping(value="showinfo")
	public String showinfo(Model model,@RequestParam("id")String _id){
		Integer id = 0;
		Trip_brands brand = null;
		List<Trip_address> address = null;
		if(_id != null){
			id = Integer.parseInt(_id);
		}
		try {
			brand = indexService.getBrandById(id);
			address = indexService.getAddress();
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("address",address);
		model.addAttribute("brand",brand);
		return "index/introduction";
	}
	
	@RequestMapping(value="pay")
	public String pay(Model model,@RequestParam(value="usingDate",required=false)String date,@RequestParam(value="title",required=false)String title,
						@RequestParam(value="b_count",required=false)Integer b_count,@RequestParam(value="area",required=false)String area,
						@RequestParam(value="count",required=false)String _count,HttpSession session){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		if(user == null){
			return "redirect:/user/login";
		}
		logger.debug("usingDate=====================>"+date);
		logger.debug("title==========================>"+title);
		logger.debug("b_count=======================>"+b_count);
		logger.debug("area=========================>"+area);
		logger.debug("count=======================>"+_count);
		Integer count = 0;
		if(_count != null){
			count = Integer.parseInt(_count);
		}
		Trip_brands brand = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date usingDate = null;
		double totalPrice = 0;
		try {
			usingDate = sdf.parse(date);
			brand = indexService.getBrandsByAreaOrUsingDate(usingDate, title);
			totalPrice = count*brand.getPrice();
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("totalPrice",totalPrice);
		model.addAttribute("count",count);
		model.addAttribute("area",area);
		model.addAttribute("brand", brand);
		model.addAttribute("b_count",b_count);
		return "index/pay";
	}
	
	@RequestMapping(value="/save")
	public String save(@RequestParam(value="t_Name",required=false)String[] t_Name,
					@RequestParam(value="title",required=false)String title,
					@RequestParam(value="usingDate",required=false)String _usingDate,
					@RequestParam(value="price",required=false)Double price,
					@RequestParam(value="count",required=false)String _count,
					@RequestParam(value="totalPrice",required=false)Double totalPrice,
					@RequestParam(value="contact",required=false)String contact,
					@RequestParam(value="phone",required=false)String phone,
					@RequestParam(value="ID_Card")String[] ID_Card,
					@RequestParam(value="t_Phone")String[] t_phone,Model model,@RequestParam(value="isPay")String _isPay,
					@RequestParam(value="org_pic",required=false)String org_pic,
					@RequestParam(value="p_createBy")String p_createBy,HttpSession session){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		logger.debug("userCode===================>"+user.getUserCode());
		logger.debug("price======================>"+price);
		String b_Code = game(10);
		logger.debug("b_Code======================>"+b_Code);
		logger.debug("isPay======================>"+_isPay);
		logger.debug("org_pic=====================>"+org_pic);
		logger.debug("p_createBy=================>"+p_createBy);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date usingDate = null;
		Integer count = 0;
		Integer isPay = 0;
		if(_isPay != null){
			isPay = Integer.parseInt(_isPay);
		}
		if(_count != null){
			count = Integer.parseInt(_count);
		}
		if(_usingDate != null){
			try {
				usingDate = sdf.parse(_usingDate);
				logger.debug("usingDate================>"+usingDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		if(indexService.add(title, usingDate, price, count, totalPrice, new Date(), user.getU_id(), 1, isPay, phone, contact, 4, user.getUserCode(),b_Code,org_pic,p_createBy)){
			logger.debug("success=========================>"+user.getU_id());
			Trip_bill bill = indexService.getBill_Id(b_Code);
			logger.debug("b_id============================>"+bill.getB_id());
			logger.debug("t_Name===========================>"+t_Name);
			for(int i=0;i<t_Name.length;i++){
				System.out.println(t_Name[i]+":idcard:"+ID_Card[i]+":t_phone:"+t_phone[i]);
				Trip_tourist tourist = new Trip_tourist();
				tourist.setCreateDate(new Date());
				tourist.setID_Card(ID_Card[i]);
				tourist.setT_Name(t_Name[i]);
				tourist.setT_phone(t_phone[i]);
				tourist.setB_id(bill.getB_id());
				tourist.setU_id(user.getU_id());
				if(indexService.addTourist(tourist)){
					logger.debug("添加成功>>>>>>>>>>>>>>>>>>>>>>");
				}
			}
			model.addAttribute("totalPrice",totalPrice);
			model.addAttribute("contact",contact);
			model.addAttribute("phone",phone);
			model.addAttribute("title",title);
			model.addAttribute("usingDate",usingDate);
			if(isPay == 1){
				return "index/success";
			}else{
				return "redirect:/user/myinfo";
			}
			
		}
		
		return "index/notsuc";
	}
	
	@RequestMapping(value="showticketinfo")
	public String showticket(Model model,@RequestParam(value="id",required=false)Integer id){
		logger.debug("id===================>"+id);
		Trip_product product = indexService.geTrip_product(id);
		model.addAttribute("product",product);
		return "index/Ticketintroduction";
	}
	
	@RequestMapping(value="ticketpay")
	public String ticketpay(Model model,@RequestParam(value="id",required=false)Integer id,
					@RequestParam(value="count")Integer count,@RequestParam("usingDate")String _usingDate,
					HttpSession session){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		if(user == null){
			return "redirect:/user/login";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date usingDate = null;
		
		try {
			usingDate = sdf.parse(_usingDate);
			logger.debug("usingDate================>"+usingDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Trip_product product = indexService.geTrip_product(id);
		double totalPrice = count*product.getPrice();
		model.addAttribute("totalPrice",totalPrice);
		model.addAttribute("product",product);
		model.addAttribute("usingDate",usingDate);
		model.addAttribute("count",count);
		return "index/Ticketpay";
	}
	
	@RequestMapping(value="saveticket")
	public String ticketsave(@RequestParam(value="t_Name",required=false)String t_Name,
			@RequestParam(value="p_Name",required=false)String p_Name,
			@RequestParam(value="usingDate",required=false)String _usingDate,
			@RequestParam(value="price",required=false)Double price,
			@RequestParam(value="count",required=false)String _count,
			@RequestParam(value="totalPrice",required=false)Double totalPrice,
			@RequestParam(value="contact",required=false)String contact,
			@RequestParam(value="phone",required=false)String phone,
			@RequestParam(value="ID_Card")String ID_Card,
			@RequestParam(value="t_Phone")String t_phone,Model model,@RequestParam(value="isPay")String _isPay,
			@RequestParam(value="org_pic")String org_pic,
			@RequestParam(value="p_createBy",required=false)String p_createBy,HttpSession session){
		
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		logger.debug("userCode===================>"+user.getUserCode());
		logger.debug("price======================>"+price);
		String b_Code = game(10);
		logger.debug("b_Code======================>"+b_Code);
		logger.debug("p_createBy===================>"+p_createBy);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date usingDate = null;
		Integer count = 0;
		Integer isPay = 0;
		if(_isPay != null){
			isPay = Integer.parseInt(_isPay);
		}
		if(_count != null){
			count = Integer.parseInt(_count);
		}
		if(_usingDate != null){
			try {
				usingDate = sdf.parse(_usingDate);
				logger.debug("usingDate================>"+usingDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(indexService.add(p_Name, usingDate, price, count, totalPrice, new Date(), user.getU_id(), 0, isPay, t_phone, contact, 1, user.getUserCode(), b_Code,org_pic,p_createBy)){
			logger.debug("success=========================>"+user.getU_id());
			Trip_bill bill = indexService.getBill_Id(b_Code);
			logger.debug("b_id============================>"+bill.getB_id());
			Trip_tourist tourist = new Trip_tourist();
			tourist.setCreateDate(new Date());
			tourist.setID_Card(ID_Card);
			tourist.setT_Name(t_Name);
			tourist.setT_phone(t_phone);
			tourist.setB_id(bill.getB_id());
			tourist.setU_id(user.getU_id());
			if(indexService.addTourist(tourist)){
				logger.debug("添加成功>>>>>>>>>>>>>>>>>>>>>>");
			}
			model.addAttribute("totalPrice",totalPrice);
			model.addAttribute("contact",contact);
			model.addAttribute("phone",phone);
			model.addAttribute("title",p_Name);
			model.addAttribute("usingDate",usingDate);
			if(isPay == 1){
				return "index/success";
			}else{
				return "redirect:/user/myinfo";
			}
			
		}
		
		return "index/Ticketpay";
	}
	
	@RequestMapping(value="showhotelinfo")
	public String showhotel(Model model,@RequestParam("id")Integer id){
		Trip_product product = indexService.geTrip_product(id);
		model.addAttribute("product",product);
		return "index/Hotelintroduction";
	}
	
	@RequestMapping(value="hotelroom")
	public String hotelroom(Model model,@RequestParam(value="id",required=false)Integer id,
			@RequestParam(value="hotelName",required=false)String hotelName,@RequestParam(value="usingDate",required=false)String _usingDate,
			@RequestParam(value="roomName",required=false)String roomName,
			@RequestParam(value="p_createBy",required=false)String p_createBy,HttpSession session){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		if(user == null){
			return "redirect:/user/login";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date usingDate = null;
		try {
			usingDate =  sdf.parse(_usingDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Trip_room room = indexService.getTrip_rooms(hotelName,roomName,usingDate);
		model.addAttribute("p_createBy",p_createBy);
		model.addAttribute("hotelName",hotelName);
		model.addAttribute("room",room);
		model.addAttribute("usingDate",usingDate);
		return "index/rooms";
	}
	
	@RequestMapping(value="selectroom")
	@ResponseBody
	public List<Trip_room> getRooms(@RequestParam("usingDate")String _usingDate,
							@RequestParam("hotelName")String hotelName){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date usingDate = null;
		String data = "";
		try {
			usingDate = sdf.parse(_usingDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.debug("usingDate=================>"+usingDate);
		Trip_room room = indexService.getTrip_rooms(hotelName, "单人房", usingDate);
		Trip_room room1 = indexService.getTrip_rooms(hotelName, "双人房", usingDate);
		List<Trip_room> list = null;
		if(room!=null && room1 != null){
			list = new ArrayList<Trip_room>();
			list.add(room);
			list.add(room1);
		}
		return list;
	}
	
	@RequestMapping(value="savehotel")
	public String saveHotel(
			@RequestParam(value="hotelName",required=false)String hotelName,
			@RequestParam(value="usingDate",required=false)String _usingDate,
			@RequestParam(value="price",required=false)Double price,
			@RequestParam(value="count",required=false)String _count,
			@RequestParam(value="contact",required=false)String contact,
			@RequestParam(value="phone",required=false)String phone,
			@RequestParam(value="rest",required=false)Integer rest,
			@RequestParam(value="room_id",required=false)Integer room_id,
			@RequestParam(value="t_Name",required=false)String[] t_Name,
			@RequestParam(value="ID_Card")String[] ID_Card,
			@RequestParam(value="t_Phone")String[] t_phone,Model model,@RequestParam(value="isPay")String _isPay,
			@RequestParam(value="org_pic",required=false)String org_pic,
			@RequestParam(value="p_createBy")String p_createBy,HttpSession session){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		logger.debug("p_createBy==================>"+p_createBy);
		logger.debug("userCode=====================>"+user.getUserCode());
		logger.debug("hotelName=====================>"+hotelName);
		logger.debug("price========================>"+price);
		logger.debug("room_id=====================>"+room_id);
		String b_Code = game(10);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date usingDate = null;
		Integer count = 0;
		Integer isPay = 0;
		if(_isPay != null){
			isPay = Integer.parseInt(_isPay);
		}
		if(_count != null){
			count = Integer.parseInt(_count);
		}
		if(_usingDate != null){
			try {
				usingDate = sdf.parse(_usingDate);
				logger.debug("usingDate================>"+usingDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		double totalPrice = count * price;
		logger.debug("totalPrice =====================>"+totalPrice);
		if(indexService.addHotelBill(hotelName, usingDate, price, count, totalPrice, new Date(), user.getU_id(), 0, room_id, isPay, phone, contact, 2, user.getUserCode(), b_Code,org_pic,p_createBy)){
			boolean flag = indexService.modifyRoomRest(rest, room_id);
			logger.debug("flag=======================>"+flag);
			logger.debug("success=========================>"+user.getU_id());
			Trip_bill bill = indexService.getBill_Id(b_Code);
			Trip_room room = indexService.getRoom_id(room_id);
			logger.debug("b_id============================>"+bill.getB_id());
			logger.debug("t_Name===========================>"+t_Name);
			for(int i=0;i<t_Name.length;i++){
				System.out.println(t_Name[i]+":idcard:"+ID_Card[i]+":t_phone:"+t_phone[i]);
				Trip_tourist tourist = new Trip_tourist();
				tourist.setCreateDate(new Date());
				tourist.setID_Card(ID_Card[i]);
				tourist.setT_Name(t_Name[i]);
				tourist.setT_phone(t_phone[i]);
				tourist.setB_id(bill.getB_id());
				tourist.setU_id(user.getU_id());
				if(indexService.addTourist(tourist)){
					logger.debug("添加成功>>>>>>>>>>>>>>>>>>>>>>");
				}
			}
			model.addAttribute("roomName",room.getRoomName());
			model.addAttribute("totalPrice",totalPrice);
			model.addAttribute("contact",contact);
			model.addAttribute("phone",phone);
			model.addAttribute("title",hotelName);
			model.addAttribute("usingDate",usingDate);
			if(isPay == 1){
				return "index/success";
			}else{
				return "redirect:/user/myinfo";
			}
			
			
		}
		return "index/success";
	}
	
	public static String game(int count){
        StringBuffer sb = new StringBuffer();
        String str = "0123456789";
        Random r = new Random();
        for(int i=0;i<count;i++){
            int num = r.nextInt(str.length());
            sb.append(str.charAt(num));
            str = str.replace((str.charAt(num)+""), "");
        }
        return sb.toString();
    }
	
	
}
